package cn.easyutil.veteran.core.error;

import java.io.Serializable;

/** 顶层异常类封装 */
public class BaseException extends RuntimeException implements Serializable {
	private static final long serialVersionUID = 6812202525292547656L;
	
	private Throwable throwable;
	private ErrorCodeDefinition errorCode;
	private String remark;
	/** 如果是web请求，此值代表数据 */
	private String requestText;
	
	public BaseException() {
		this(ErrorEnum.error);
	}

	public BaseException(ErrorCodeDefinition errorCode, String... remark) {
		super(remark==null||remark.length==0?errorCode.getRemark():remark[0]);
		this.errorCode = errorCode;
		this.remark = remark==null||remark.length==0?errorCode.getRemark():remark[0];
	}

	public BaseException(ErrorCodeDefinition errorCode, Throwable throwable, String... remark) {
		super(remark==null||remark.length==0?errorCode.getRemark():errorCode.getRemark().equals(remark[0])?remark[0]:errorCode.getRemark()+", "+remark[0], throwable);
		while(throwable instanceof BaseException) {
			BaseException temp = ((BaseException)throwable);
			throwable = temp.getThrowable();
			errorCode = temp.getErrorCode();
			if(temp.getRemark()!=null && temp.getRemark().length()>0) {
				remark = new String[1];
				remark[0] = temp.getRemark();
			}
		}
		this.errorCode = errorCode;
		this.remark = remark==null||remark.length==0?errorCode.getRemark():errorCode.getRemark()+", "+remark[0];
		this.throwable = throwable;
	}
	
	@Override
	public String getMessage() {
		return remark==null?super.getMessage():remark;
	}
	
	/** 打印异常，包括记录异常日志 */
	@Override
	public void printStackTrace() {
		if(throwable == null) {
			requestText = requestText==null?"":requestText;
		} else {
			requestText = requestText==null?"":requestText;
		}
	}
	public ErrorCodeDefinition getErrorCode() {
		return errorCode;
	}

	public Throwable getThrowable() {
		return throwable;
	}

	public String getRemark() {
		return remark;
	}
}
